<?php

class UploadAction extends CAction {
    public function run() {
        // Get configuartion data (we fill up 2 arrays - $config and $conf)

        $conf = require_once (dirname(__FILE__) . '/config.php');
//      $conf['img_path'] = Yii::app()->request->baseUrl . '/uploads/'; // Relative to domain name
//	$conf['upload_path'] = dirname(Yii::app()->basePath) . '/uploads/'; // Physical path. [Usually works fine like this]
        
        if ($conf['allow_resize'])
        {
                if ($conf['max_width'] == 0 and $conf['max_height'] == 0)
                {
                        $conf['allow_resize'] = FALSE;
                }
        }

        // Load uploader
        Yii::import('ext.tinymce.lib.Upload');
        $upload = new Upload($conf);

        if ($upload->do_upload()) // Success
        {
                // General result data
                $result = $upload->data();

                // Shall we resize an image?
                if ($conf['allow_resize'] and $conf['max_width'] > 0 and $conf['max_height'] > 0 and (($result['image_width'] > $conf['max_width']) or ($result['image_height'] > $conf['max_height'])))
                {				
                        // Resizing parameters
                        $resizeParams = array
                        (
                            'source_image'	=> $result['full_path'],
                            'new_image'		=> $result['full_path'],
                            'width'			=> $conf['max_width'],
                            'height'		=> $conf['max_height']
                        );

                        // Load resize library
                        Yii::import('ext.tinymce.lib.Image_lib');
                        $image_lib = new Image_lib($resizeParams);

                        // Do resize
                        $image_lib->resize();
                }

                // Add our stuff
                $result['result']		= "file_uploaded";
                $result['resultcode']	= 'ok';
                $result['file_name']	= $conf['img_path'] . '/' . $result['file_name'];

                // Output to user
                $this->getController()->renderFile(dirname(__FILE__) . '/views/ajax_upload_result.php', $result);
                
        }
        else // Failure
        {
                // Compile data for output
                $result['result']		= $upload->display_errors(' ', ' ');
                $result['resultcode']	= 'failed';
                $result['file_name']	= '';

                // Output to user
                $this->getController()->renderFile(dirname(__FILE__) . '/views/ajax_upload_result.php', $result);
        }
    }
}